import DlyAdminUser from '../../model/dlyadminuser'
import jwt from 'jsonwebtoken'
import bcrypt from 'bcryptjs'
import { jwtConfig } from '../../config/index'
import ApiError from '../../error/ApiError'
import ApiErrorNames from '../../error/ApiErrorNames'
class UserController {
	static async addAdminUser(ctx) {
		const requestBody = ctx.request.body
		if (!requestBody || !requestBody.phone || !requestBody.password) {
			throw new ApiError(ApiErrorNames.RegistryNameEndPassNotNull)
		}
		const user = await DlyAdminUser.findOne({ phone: requestBody.phone })
		if (user) {
			throw new ApiError(ApiErrorNames.RegistryUserisExist)
		}
		const salt = bcrypt.genSaltSync(10)
		const endPass = bcrypt.hashSync(requestBody.password, salt)
		const newUser = new DlyAdminUser({
			phone: requestBody.phone,
			password: endPass,
			role: requestBody.role || 'admin',
			roleName: requestBody.roleName || 'admin',
			status: 1,
			userName: requestBody.userName || '自建管理员',
			point: requestBody.point || 0,
			channelCode: requestBody.channelCode || '',
		})
		await newUser.save()
		ctx.body = '添加成功'
	}
	static async registry(ctx) {
		const requestBody = ctx.request.body
		if (!requestBody || !requestBody.phone || !requestBody.password) {
			throw new ApiError(ApiErrorNames.RegistryNameEndPassNotNull)
		}
		// 判断当前用户是否有添加用户的权限
		const salt = bcrypt.genSaltSync(10)
		// 哈希加密
		const hash = bcrypt.hashSync(requestBody.password, salt)
		const getUser = await DlyAdminUser.findOne({ phone: requestBody.phone })
		// 需要检查用户是否有权限添加
		if (!getUser) {
			delete requestBody.password
			const adduserinfodata = {
				phone: requestBody.phone || '',
				role: requestBody.role || '',
				status: requestBody.status || 0,
				userName: requestBody.userName || '',
				roleName: requestBody.roleName || '',
				point: requestBody.point || 0,
				channelCode: requestBody.channelCode || '',
			}
			const newUser = new DlyAdminUser({
				parentId: ctx.request.header.jwtuserinfo._id || '',
				...adduserinfodata,
				password: hash,
			})
			await newUser.save()
			ctx.body = '新增成功'
			return
		}
		throw new ApiError(ApiErrorNames.RegistryUserisExist)
	}
	static async login(ctx) {
		const requestBody = ctx.request.body
		if (!requestBody || !requestBody.phone || !requestBody.password) {
			throw new ApiError(ApiErrorNames.LoginPhoneNotNull)
		}

		const getUser = await DlyAdminUser.findOne({ phone: requestBody.phone })
		if (!getUser) {
			throw new ApiError(ApiErrorNames.LoginNotUser)
		}
		const isMatch = bcrypt.compareSync(
			requestBody.password,
			getUser.password
		)
		if (isMatch) {
			const token = jwt.sign({ ...getUser._doc }, jwtConfig.secret, {
				expiresIn: '30d',
			})
			ctx.body = { token }
			return
			// 返回token
		}
		throw new ApiError(ApiErrorNames.LoginUserPassErr)
	}
	static async changePassword(ctx) {
		const requestBody = ctx.request.body
		if (
			!requestBody ||
			!requestBody.oldpass ||
			!requestBody.newpass ||
			!requestBody.confirmpass
		) {
			throw new ApiError(ApiErrorNames.SetPassDataNull)
		}
		const jwtdata = ctx.request.header.jwtuserinfo
		const getUser = await DlyAdminUser.findOne({ _id: jwtdata._id })
		const isMatch = bcrypt.compareSync(
			requestBody.oldpass,
			getUser.password
		)
		if (!isMatch) {
			throw new ApiError(ApiErrorNames.OldPassErr)
		}
		if (requestBody.newpass !== requestBody.confirmpass) {
			throw new ApiError(ApiErrorNames.StePassConfirmpassDontMatch)
		}
		const salt = bcrypt.genSaltSync(10)
		const hash = bcrypt.hashSync(requestBody.newpass, salt)
		const updateUser = await DlyAdminUser.updateOne(
			{ _id: jwtdata._id },
			{ password: hash }
		)
		if (updateUser.nModified > 0) {
			ctx.body = '密码修改成功'
			return
		}
		throw new ApiError(ApiErrorNames.UnknownError)
	}
	static async getUserInfo(ctx) {
		const jwtdata = ctx.request.header.jwtuserinfo
		// if(jwtdata) delete jwtdata.password
		const thisuserinfo = await DlyAdminUser.findOne({ _id: jwtdata._id })
		delete thisuserinfo.password
		ctx.body = thisuserinfo
		// throw new ApiError(ApiErrorNames.UserNameNotNull);
	}
	static async changeUserInfo(ctx) {
		const _id = ctx.request.header.jwtuserinfo._id
		const format = {}
		ctx.request.body.password = ''
		ctx.request.body.phone = ''
		for (let key in ctx.request.body) {
			if (ctx.request.body[key]) {
				format[key] = ctx.request.body[key]
			}
		}
		const updateUser = await DlyAdminUser.updateOne({ _id }, format)
		if (updateUser.nModified > 0) {
			ctx.body = '修改成功'
			return
		}
		throw new ApiError(ApiErrorNames.UnknownError)
	}
	static async getAgentsUserList(ctx) {
		const userid = ctx.request.header.jwtuserinfo._id
		const roleName = ctx.request.header.jwtuserinfo.roleName
		const {
			page = 1,
			pageSize = 20,
			phone = '',
			status = '',
			userName = '',
			_id = '',
			proxyPhone = '',
		} = ctx.request.query
		let parentId =
			roleName === 'adminSp' || roleName === 'admin' ? '' : userid
		if (proxyPhone) {
			const proxyUser = await DlyAdminUser.findOne({ phone: proxyPhone })
			console.log('proxyUser', proxyUser)
			if (proxyUser) {
				parentId = proxyUser._id
			} else {
				ctx.body = {
					list: [],
					// 总数
					total: 0,
				}
				return
				// throw new ApiError(ApiErrorNames.NoProxyId)
			}
		}
		const param = {
			phone: phone && new RegExp(phone, 'i'),
			status,
			userName: userName && new RegExp(userName, 'i'),
			parentId,
			_id,
		}
		for (let key in param) {
			if (!param[key]) {
				delete param[key]
			}
		}
		param.deleted = false
		try {
			const userList = await DlyAdminUser.find(param)
				// 关联查询
				.populate('parentId')
				.limit(pageSize * 1)
				.skip((page - 1) * pageSize)
			const total = await DlyAdminUser.countDocuments(param)
			ctx.body = {
				list: userList,
				// 总数
				total,
			}
		} catch (error) {
			ctx.body = {
				list: [],
				// 总数
				total: 0,
			}
		}
	}
	static async deleteAgentsUser(ctx) {
		// ctx.verifyParams({
		//     _id: { type: 'string', required: true },
		// })

		if (!ctx.request.query._id)
			throw new ApiError(ApiErrorNames.NoParamsData)

		const { _id } = ctx.request.query
		// const updateUser = await DlyAdminUser.remove({ _id })

		// if(updateUser.deletedCount > 0) {
		// 	ctx.body = '删除成功'
		// 	return
		// }
		const updateUser = await DlyAdminUser.updateOne(
			{ _id },
			{
				deleted: true,
				phone: '',
			}
		)
		if (updateUser.ok === 1) {
			ctx.body = '删除成功'
			return
		}
		throw new ApiError(ApiErrorNames.UnknownError)
	}
	static async editAgentsUserInfo(ctx) {
		const requestBody = ctx.request.body
		const { _id, ...rest } = requestBody
		if (!_id) throw new ApiError(ApiErrorNames.NoParamsData)
		const findUser = await DlyAdminUser.findOne({ _id })
		const updataInfo = {
			userName: rest.userName,
			status: rest.status,
			role: rest.role,
			point: rest.point,
			channelCode: rest.channelCode,
		}
		if (findUser.password !== rest.password) {
			const salt = bcrypt.genSaltSync(10)
			// 哈希加密
			const hash = bcrypt.hashSync(rest.password, salt)
			updataInfo.password = hash
		}
		const updateUser = await DlyAdminUser.updateOne({ _id }, updataInfo)
		if (updateUser.ok === 1) {
			ctx.body = '修改成功'
			return
		}
		throw new ApiError(ApiErrorNames.UnknownError)
	}
}

export default UserController
